package org.ccvi.policy.entity.userinfo;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.ccvi.policy.entity.userinfo.Resource;
import org.ccvi.policy.entity.userinfo.Identity;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.springside.modules.utils.ReflectionUtils;

@Entity
@Table(name = "pol_role")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Role extends Identity {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1543981850142136329L;
	
	private Set<Resource> resources = new LinkedHashSet<Resource>();

	@ManyToMany
	@JoinTable(name = "id_role_resource", joinColumns = { @JoinColumn(name = "role_id") }, inverseJoinColumns = { @JoinColumn(name = "resource_id") })
	@Fetch(FetchMode.SUBSELECT)
	@OrderBy("position")
	@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
	public Set<Resource> getResources() {
		return resources;
	}

	public void setResources(Set<Resource> resources) {
		this.resources = resources;
	}

	@SuppressWarnings("unchecked")
	@Transient
	public List<Long> getResourceIds() {
		return ReflectionUtils.fetchElementPropertyToList(resources, "id");
	}

	@SuppressWarnings("unchecked")
	@Transient
	public List<Long> getResourceNames() {
		return ReflectionUtils.fetchElementPropertyToList(resources, "name");
	}
}
